package Wires.diagram.edit.parts;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.MatchResult;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.draw2d.FlowLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.RoundedRectangle;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.FlowLayoutEditPolicy;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IBorderItemEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.BorderItemSelectionEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CreationEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.graphics.Color;

import Wires.LibraryRef;
import Wires.QueryType;
import Wires.WiresFactory;
import Wires.WiresPackage;

/**
 * @generated
 */
public class QueryTypeEditPart extends AbstractBorderedShapeEditPart {

	/**
	 * @generated
	 */
	public static final int VISUAL_ID = 1014;

	/**
	 * @generated
	 */
	protected IFigure contentPane;

	/**
	 * @generated
	 */
	protected IFigure primaryShape;

	/**
	 * @generated
	 */
	public QueryTypeEditPart(View view) {
		super(view);
	}

	/**
	 * @generated
	 */
	protected void createDefaultEditPolicies() {
		installEditPolicy(EditPolicyRoles.CREATION_ROLE,
				new CreationEditPolicy());
		super.createDefaultEditPolicies();
		installEditPolicy(
				EditPolicyRoles.SEMANTIC_ROLE,
				new Wires.diagram.edit.policies.QueryTypeItemSemanticEditPolicy());
		installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE,
				new DragDropEditPolicy());
		installEditPolicy(EditPolicyRoles.CANONICAL_ROLE,
				new Wires.diagram.edit.policies.QueryTypeCanonicalEditPolicy());
		installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());
		// XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies
		// removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE);
	}

	/**
	 * @generated
	 */
	protected LayoutEditPolicy createLayoutEditPolicy() {

		FlowLayoutEditPolicy lep = new FlowLayoutEditPolicy() {

			protected EditPolicy createChildEditPolicy(EditPart child) {
				if (child instanceof IBorderItemEditPart) {
					return new BorderItemSelectionEditPolicy();
				}
				return super.createChildEditPolicy(child);
			}

			protected Command createAddCommand(EditPart child, EditPart after) {
				return null;
			}

			protected Command createMoveChildCommand(EditPart child,
					EditPart after) {
				return null;
			}

			protected Command getCreateCommand(CreateRequest request) {
				return null;
			}
		};
		return lep;
	}

	/**
	 * @generated
	 */
	protected IFigure createNodeShape() {
		QueryTypeFigure figure = new QueryTypeFigure();
		return primaryShape = figure;
	}

	/**
	 * @generated
	 */
	public QueryTypeFigure getPrimaryShape() {
		return (QueryTypeFigure) primaryShape;
	}

	/**
	 * @generated
	 */
	protected boolean addFixedChild(EditPart childEditPart) {
		if (childEditPart instanceof Wires.diagram.edit.parts.QueryTypeNameEditPart) {
			((Wires.diagram.edit.parts.QueryTypeNameEditPart) childEditPart)
					.setLabel(getPrimaryShape().getFigureQueryTypeNameFigure());
			return true;
		}
		if (childEditPart instanceof Wires.diagram.edit.parts.InputFormalParameterEditPart) {
			BorderItemLocator locator = new BorderItemLocator(getMainFigure(),
					PositionConstants.NORTH);
			getBorderedFigure()
					.getBorderItemContainer()
					.add(
							((Wires.diagram.edit.parts.InputFormalParameterEditPart) childEditPart)
									.getFigure(), locator);
			return true;
		}
		if (childEditPart instanceof Wires.diagram.edit.parts.OutputFormalParameterEditPart) {
			BorderItemLocator locator = new BorderItemLocator(getMainFigure(),
					PositionConstants.SOUTH);
			getBorderedFigure()
					.getBorderItemContainer()
					.add(
							((Wires.diagram.edit.parts.OutputFormalParameterEditPart) childEditPart)
									.getFigure(), locator);
			return true;
		}
		if (childEditPart instanceof Wires.diagram.edit.parts.LibraryRef2EditPart) {
			BorderItemLocator locator = new BorderItemLocator(getMainFigure(),
					PositionConstants.EAST);
			getBorderedFigure()
					.getBorderItemContainer()
					.add(
							((Wires.diagram.edit.parts.LibraryRef2EditPart) childEditPart)
									.getFigure(), locator);
			return true;
		}
		return false;
	}

	/**
	 * @generated
	 */
	protected boolean removeFixedChild(EditPart childEditPart) {

		if (childEditPart instanceof Wires.diagram.edit.parts.InputFormalParameterEditPart) {
			getBorderedFigure()
					.getBorderItemContainer()
					.remove(
							((Wires.diagram.edit.parts.InputFormalParameterEditPart) childEditPart)
									.getFigure());
			return true;
		}
		if (childEditPart instanceof Wires.diagram.edit.parts.OutputFormalParameterEditPart) {
			getBorderedFigure()
					.getBorderItemContainer()
					.remove(
							((Wires.diagram.edit.parts.OutputFormalParameterEditPart) childEditPart)
									.getFigure());
			return true;
		}
		if (childEditPart instanceof Wires.diagram.edit.parts.LibraryRef2EditPart) {
			getBorderedFigure()
					.getBorderItemContainer()
					.remove(
							((Wires.diagram.edit.parts.LibraryRef2EditPart) childEditPart)
									.getFigure());
			return true;
		}
		return false;
	}

	/**
	 * @generated
	 */
	protected void addChildVisual(EditPart childEditPart, int index) {
		if (addFixedChild(childEditPart)) {
			return;
		}
		super.addChildVisual(childEditPart, -1);
	}

	/**
	 * @generated
	 */
	protected void removeChildVisual(EditPart childEditPart) {
		if (removeFixedChild(childEditPart)) {
			return;
		}
		super.removeChildVisual(childEditPart);
	}

	/**
	 * @generated
	 */
	protected IFigure getContentPaneFor(IGraphicalEditPart editPart) {

		if (editPart instanceof Wires.diagram.edit.parts.InputFormalParameterEditPart) {
			return getBorderedFigure().getBorderItemContainer();
		}
		if (editPart instanceof Wires.diagram.edit.parts.OutputFormalParameterEditPart) {
			return getBorderedFigure().getBorderItemContainer();
		}
		if (editPart instanceof Wires.diagram.edit.parts.LibraryRef2EditPart) {
			return getBorderedFigure().getBorderItemContainer();
		}
		return super.getContentPaneFor(editPart);
	}

	/**
	 * @generated
	 */
	protected NodeFigure createNodePlate() {
		DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(getMapMode()
				.DPtoLP(40), getMapMode().DPtoLP(40));
		return result;
	}

	/**
	 * Creates figure for this edit part.
	 * 
	 * Body of this method does not depend on settings in generation model
	 * so you may safely remove <i>generated</i> tag and modify it.
	 * 
	 * @generated
	 */
	protected NodeFigure createMainFigure() {
		NodeFigure figure = createNodePlate();
		figure.setLayoutManager(new StackLayout());
		IFigure shape = createNodeShape();
		figure.add(shape);
		contentPane = setupContentPane(shape);
		return figure;
	}

	/**
	 * Default implementation treats passed figure as content pane.
	 * Respects layout one may have set for generated figure.
	 * @param nodeShape instance of generated figure class
	 * @generated
	 */
	protected IFigure setupContentPane(IFigure nodeShape) {
		if (nodeShape.getLayoutManager() == null) {
			ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout();
			layout.setSpacing(getMapMode().DPtoLP(5));
			nodeShape.setLayoutManager(layout);
		}
		return nodeShape; // use nodeShape itself as contentPane
	}

	/**
	 * @generated
	 */
	public IFigure getContentPane() {
		if (contentPane != null) {
			return contentPane;
		}
		return super.getContentPane();
	}

	/**
	 * @generated
	 */
	public EditPart getPrimaryChildEditPart() {
		return getChildBySemanticHint(Wires.diagram.part.WiresVisualIDRegistry
				.getType(Wires.diagram.edit.parts.QueryTypeNameEditPart.VISUAL_ID));
	}

	/**
	 * @generated NOT
	 */
	//@Override
	protected void handleNotificationEvent(Notification notification) {
		if (notification.getEventType() == Notification.SET
				&& notification.getFeature() == WiresPackage.Literals.TYPE__PATH) {
			QueryType query = ((QueryType) ((View) this.getModel())
					.getElement());
			String stringPath = ResourcesPlugin.getWorkspace().getRoot()
					.getLocation()
					+ query.getPath();
			if (stringPath != null) {
				Path path = new Path(stringPath);
				if (path.toFile().isFile()) {
					//Borramos todas sus librerias
					query.getLibraries().clear();
					//Creamos sus nuevas librerias
					createLibs(stringPath);
				}
			}
		}
		super.handleNotificationEvent(notification);
	}

	/**
	 * @generated NOT
	 */
	protected String nextNoDelimToken(StringTokenizer tokens) {
		String result = null;
		if (tokens.hasMoreTokens())
			result = tokens.nextToken();
		while (tokens.hasMoreTokens()
				&& (result.equals(" ") || result.equals(",") || result
						.equals(":"))) {
			result = tokens.nextToken();
		}
		return result;
	}

	/**
	 * @generated NOT
	 */
	protected void createLibs(String stringPath) {
		QueryType query = ((QueryType) ((View) this.getModel()).getElement());
		try {
			BufferedReader br = new BufferedReader(new FileReader(stringPath));
			String file = "", line, word;
			while ((line = br.readLine()) != null)
				file = file + " " + line;
			StringTokenizer tokens = new StringTokenizer(file, " ,:;", true);
			while (tokens.hasMoreTokens()) {
				word = tokens.nextToken();
				System.out.println(word);
				if (word.equals("uses") && tokens.hasMoreTokens()) {
					word = nextNoDelimToken(tokens);
					while (!word.equals(";") && tokens.hasMoreTokens()) {
						//Crear libreria
						LibraryRef lib = WiresFactory.eINSTANCE
								.createLibraryRef();
						lib.setName(word);
						query.getLibraries().add(lib);
						//Continuamos
						word = nextNoDelimToken(tokens);
					}
				}
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @generated
	 */
	public class QueryTypeFigure extends RoundedRectangle {

		/**
		 * @generated
		 */
		private WrappingLabel fFigureQueryTypeNameFigure;

		/**
		 * @generated
		 */
		public QueryTypeFigure() {

			FlowLayout layoutThis = new FlowLayout();
			layoutThis.setStretchMinorAxis(false);
			layoutThis.setMinorAlignment(FlowLayout.ALIGN_LEFTTOP);

			layoutThis.setMajorAlignment(FlowLayout.ALIGN_LEFTTOP);
			layoutThis.setMajorSpacing(5);
			layoutThis.setMinorSpacing(5);
			layoutThis.setHorizontal(true);

			this.setLayoutManager(layoutThis);

			this.setCornerDimensions(new Dimension(getMapMode().DPtoLP(30),
					getMapMode().DPtoLP(30)));
			this.setBackgroundColor(THIS_BACK);

			this.setBorder(new MarginBorder(getMapMode().DPtoLP(5),
					getMapMode().DPtoLP(5), getMapMode().DPtoLP(5),
					getMapMode().DPtoLP(5)));
			createContents();
		}

		/**
		 * @generated
		 */
		private void createContents() {

			fFigureQueryTypeNameFigure = new WrappingLabel();
			fFigureQueryTypeNameFigure.setText("<name>");

			this.add(fFigureQueryTypeNameFigure);

		}

		/**
		 * @generated
		 */
		private boolean myUseLocalCoordinates = false;

		/**
		 * @generated
		 */
		protected boolean useLocalCoordinates() {
			return myUseLocalCoordinates;
		}

		/**
		 * @generated
		 */
		protected void setUseLocalCoordinates(boolean useLocalCoordinates) {
			myUseLocalCoordinates = useLocalCoordinates;
		}

		/**
		 * @generated
		 */
		public WrappingLabel getFigureQueryTypeNameFigure() {
			return fFigureQueryTypeNameFigure;
		}

	}

	/**
	 * @generated
	 */
	static final Color THIS_BACK = new Color(null, 255, 187, 107);

}
